<script lang="ts" setup>
import { nextTick, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { logger } from 'common-utils';

withDefaults(
  defineProps<{
    loading?: boolean;
  }>(),
  {
    loading: false,
  },
);

const emit = defineEmits<{
  (e: 'confirm', data: any): void;
  (e: 'update:loading', data: any): void;
}>();

const isConfirmLoading = ref(false);

const data = ref({
  title: '',
  schema: {},
});
const formRef = ref();

const formBinding = ref();

const [Modal, modalApi] = useVbenModal({
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>() || {};

      formBinding.value = data.value.schema || {};

      nextTick(() => {});
    }
    isConfirmLoading.value = false;
  },
  async onConfirm() {
    isConfirmLoading.value = true;

    try {
      await formRef.value?.submit();
      emit('confirm', formRef.value.form);
    } catch (error) {
      logger.error('', error);
    } finally {
      isConfirmLoading.value = false;
    }
  },
});
</script>
<template>
  <Modal :confirm-loading="loading" :loading="loading" :title="data.title">
    <fs-form v-if="formBinding.columns" ref="formRef" v-bind="formBinding" />
  </Modal>
</template>
